package com.jiuyuan.config;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @program: hrms
 * @description: Authorities的类型是<? extents GrantedAuthority>的，但json不知道是什么，需要我们自定义序列化器
 * @author: Feng
 * @create: 2023-02-20 06:18
 **/

public class CustomAuthorityDesirializer extends JsonDeserializer {
    @Override
    public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {
        ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec();
        JsonNode jsonNode = mapper.readTree(jsonParser);
        Iterator<JsonNode> elements = jsonNode.elements();


        List<GrantedAuthority> authorities = new ArrayList<>();
        while(elements.hasNext()){
            JsonNode element = elements.next();
            JsonNode authority = element.get("authority");
            authorities.add(new SimpleGrantedAuthority(authority.asText()));
        }


        return authorities;
    }
}
